/**
 * Agent Designer Demo
 * 
 * Demonstrates the Agent Designer API functionality
 */

const BASE_URL = 'http://localhost:3000';

interface AgentConfig {
  id: string;
  name: string;
  description: string;
  model: string;
  workflow: {
    nodes: any[];
    edges: any[];
  };
  version: number;
}

/**
 * Make HTTP request
 */
async function request(method: string, path: string, body?: any): Promise<any> {
  const url = `${BASE_URL}${path}`;
  const options: RequestInit = {
    method,
    headers: {
      'Content-Type': 'application/json',
    },
  };

  if (body) {
    options.body = JSON.stringify(body);
  }

  const response = await fetch(url, options);
  return response.json();
}

/**
 * Demo: List templates
 */
async function demoListTemplates() {
  console.log('\n📋 Demo: List Templates');
  console.log('='.repeat(50));

  const result = await request('GET', '/api/agents/templates/list');
  console.log(`Found ${result.templates.length} templates:`);
  
  result.templates.forEach((template: any) => {
    console.log(`  - ${template.name} (${template.category})`);
    console.log(`    ${template.description}`);
  });
}

/**
 * Demo: Create agent from template
 */
async function demoCreateFromTemplate(): Promise<string> {
  console.log('\n🎨 Demo: Create Agent from Template');
  console.log('='.repeat(50));

  const agent = await request('POST', '/api/agents/templates/customer-service', {
    name: 'My Customer Service Bot',
  });

  console.log(`✅ Created agent: ${agent.name}`);
  console.log(`   ID: ${agent.id}`);
  console.log(`   Model: ${agent.model}`);
  console.log(`   Version: ${agent.version}`);

  return agent.id;
}

/**
 * Demo: Create custom agent
 */
async function demoCreateCustomAgent(): Promise<string> {
  console.log('\n🔧 Demo: Create Custom Agent');
  console.log('='.repeat(50));

  const agent = await request('POST', '/api/agents', {
    name: 'Data Processing Agent',
    description: 'Processes data through a workflow',
    systemPrompt: {
      type: 'text',
      content: 'You are a data processing agent. Analyze and transform data efficiently.',
    },
    model: 'claude-sonnet-4',
    workflow: {
      nodes: [
        {
          id: 'input-1',
          type: 'input',
          position: { x: 0, y: 0 },
          data: { label: 'Input Data', description: 'Receive input data' },
        },
        {
          id: 'validate-1',
          type: 'processing',
          position: { x: 200, y: 0 },
          data: { label: 'Validate', description: 'Validate data format' },
        },
        {
          id: 'transform-1',
          type: 'processing',
          position: { x: 400, y: 0 },
          data: { label: 'Transform', description: 'Transform data' },
        },
        {
          id: 'output-1',
          type: 'output',
          position: { x: 600, y: 0 },
          data: { label: 'Output Result', description: 'Return processed data' },
        },
      ],
      edges: [
        { id: 'edge-1', source: 'input-1', target: 'validate-1' },
        { id: 'edge-2', source: 'validate-1', target: 'transform-1' },
        { id: 'edge-3', source: 'transform-1', target: 'output-1' },
      ],
    },
    settings: {
      contextStrategy: 'full',
      maxTurns: 20,
      temperature: 0.5,
    },
  });

  console.log(`✅ Created agent: ${agent.name}`);
  console.log(`   ID: ${agent.id}`);
  console.log(`   Workflow nodes: ${agent.workflow.nodes.length}`);
  console.log(`   Workflow edges: ${agent.workflow.edges.length}`);

  return agent.id;
}

/**
 * Demo: Validate workflow
 */
async function demoValidateWorkflow(agentId: string) {
  console.log('\n✅ Demo: Validate Workflow');
  console.log('='.repeat(50));

  const result = await request('POST', `/api/agents/${agentId}/validate`);

  console.log(`Validation result: ${result.valid ? '✅ Valid' : '❌ Invalid'}`);
  
  if (result.errors.length > 0) {
    console.log('\nErrors:');
    result.errors.forEach((error: any) => {
      console.log(`  ❌ ${error.message}`);
    });
  }

  if (result.warnings.length > 0) {
    console.log('\nWarnings:');
    result.warnings.forEach((warning: any) => {
      console.log(`  ⚠️  ${warning.message}`);
    });
  }

  if (result.valid && result.errors.length === 0 && result.warnings.length === 0) {
    console.log('  No errors or warnings!');
  }
}

/**
 * Demo: List all agents
 */
async function demoListAgents() {
  console.log('\n📊 Demo: List All Agents');
  console.log('='.repeat(50));

  const result = await request('GET', '/api/agents');

  console.log(`Total agents: ${result.total}`);
  console.log(`Page: ${result.page} (${result.pageSize} per page)`);
  console.log('\nAgents:');

  result.agents.forEach((agent: AgentConfig) => {
    console.log(`  - ${agent.name} (v${agent.version})`);
    console.log(`    ID: ${agent.id}`);
    console.log(`    Model: ${agent.model}`);
    console.log(`    Nodes: ${agent.workflow.nodes.length}, Edges: ${agent.workflow.edges.length}`);
  });
}

/**
 * Demo: Update agent
 */
async function demoUpdateAgent(agentId: string) {
  console.log('\n🔄 Demo: Update Agent');
  console.log('='.repeat(50));

  const agent = await request('PUT', `/api/agents/${agentId}`, {
    name: 'Updated Data Processing Agent',
    description: 'Updated description with new features',
    settings: {
      temperature: 0.7,
    },
  });

  console.log(`✅ Updated agent: ${agent.name}`);
  console.log(`   Version: ${agent.version}`);
  console.log(`   Temperature: ${agent.settings.temperature}`);
}

/**
 * Demo: Duplicate agent
 */
async function demoDuplicateAgent(agentId: string): Promise<string> {
  console.log('\n📋 Demo: Duplicate Agent');
  console.log('='.repeat(50));

  const agent = await request('POST', `/api/agents/${agentId}/duplicate`, {
    name: 'Duplicated Agent',
  });

  console.log(`✅ Duplicated agent: ${agent.name}`);
  console.log(`   Original ID: ${agentId}`);
  console.log(`   New ID: ${agent.id}`);
  console.log(`   Version: ${agent.version}`);

  return agent.id;
}

/**
 * Demo: Delete agent
 */
async function demoDeleteAgent(agentId: string) {
  console.log('\n🗑️  Demo: Delete Agent');
  console.log('='.repeat(50));

  const result = await request('DELETE', `/api/agents/${agentId}`);

  if (result.success) {
    console.log(`✅ Deleted agent: ${agentId}`);
  } else {
    console.log(`❌ Failed to delete agent: ${agentId}`);
  }
}

/**
 * Main demo
 */
async function main() {
  console.log('\n🚀 Agent Designer API Demo');
  console.log('='.repeat(50));

  try {
    // 1. List templates
    await demoListTemplates();

    // 2. Create agent from template
    const templateAgentId = await demoCreateFromTemplate();

    // 3. Create custom agent with workflow
    const customAgentId = await demoCreateCustomAgent();

    // 4. Validate workflow
    await demoValidateWorkflow(customAgentId);

    // 5. List all agents
    await demoListAgents();

    // 6. Update agent
    await demoUpdateAgent(customAgentId);

    // 7. Duplicate agent
    const duplicatedAgentId = await demoDuplicateAgent(customAgentId);

    // 8. List agents again
    await demoListAgents();

    // 9. Delete duplicated agent
    await demoDeleteAgent(duplicatedAgentId);

    // 10. Final list
    await demoListAgents();

    console.log('\n✅ Demo completed successfully!');
    console.log('='.repeat(50));

  } catch (error) {
    console.error('\n❌ Demo failed:', error);
    process.exit(1);
  }
}

// Run demo
main();

